package com.sky.controller.admin;

import com.sky.po.CompleteEx;
import com.sky.po.ExcelVo;
import com.sky.po.RequestData;
import com.sky.po.SmallDaochuRequest;
import com.sky.result.Result;
import com.sky.service.FileService;
import com.sky.vo.BusinessDataVO;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
import org.bytedeco.opencv.presets.opencv_core;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;


    /**
     *  导入前显示表格（单表）
     */
    @PostMapping("/importExcel")
    public Result<List<ExcelVo>> importExcel(@RequestParam("file") MultipartFile excel) throws Exception {
        List<ExcelVo> excelVoList = fileService.importExcel(excel);
        //System.out.println("excel解析："+excelVoList);
        return Result.success(excelVoList);
    }

    /**
     * 提交（单表）导入数据
     * @param requestData
     * @return
     */
    @PostMapping("/submitdaoru")
    public Result submitdaoru(@RequestBody RequestData requestData){
        //System.out.println("接收到的表单数据：" + requestData.getData());
        //System.out.println("选中的选项：" + requestData.getSelectedOption());
        List<ExcelVo> list=requestData.getData();
        String status= requestData.getSelectedOption();
        int i=0;
        for (ExcelVo vo : list) {
            CompleteEx completeEx=new CompleteEx();
            BeanUtils.copyProperties(vo,completeEx);
            completeEx.setStatus(Integer.parseInt(status));
            //System.out.println(completeEx);
            if (completeEx.getQname()!=null && !completeEx.getQname().isEmpty()){
                fileService.daorumany(completeEx);
                i=i+1;
            }

        }
        return Result.success(i);
    }

    /**
     * 导出
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/smalldaochu")
    public ResponseEntity<Integer> handleSmallDaochuRequest(@RequestBody SmallDaochuRequest request, HttpServletResponse response) {
        // 处理接收到的数据
        String status = request.getStatus();
        String qname = request.getQname();
        List<String> qpositionList = request.getQpositionList();

        if (status.equals("0")){
            //List<CompleteEx> allList=fileService.getAll();
            excelBigDaochu(response);
            return ResponseEntity.status(HttpStatus.OK).body(36);
        }else {
            // 进行处理...
            List<CompleteEx> list = fileService.smallfileter(status, qname, qpositionList);
            int processedCount = list.size();
            excelSmallDaochu(response,list);
            //excelSmallDaochu(response,list);
            return ResponseEntity.status(HttpStatus.OK).body(processedCount);
        }

    }
//    @PostMapping("/daochu")
//    public ResponseEntity<Integer> handleSmallDaochuRequest(@RequestBody SmallDaochuRequest request, HttpServletResponse response) {
//        // 处理接收到的数据
//        String status = request.getStatus();
//        List<String> column = request.getColumn();
//        List<String> qpositionList = request.getQpositionList();
//        System.out.println("status="+status+" column="+column+" qpositionList="+qpositionList);
//        if (status.equals("0")){
//            //List<CompleteEx> allList=fileService.getAll();
//            excelBigDaochu(response);
//            return ResponseEntity.status(HttpStatus.OK).body(39);
//        }else {
//            // 进行处理...
//            List<CompleteEx> list = fileService.smallfileter(status,qpositionList);
//            int processedCount = list.size();
//            excelSmallDaochu(response,list,column);
//            //excelSmallDaochu(response,list);
//            return ResponseEntity.status(HttpStatus.OK).body(processedCount);
//        }
//
//
//    }
    /**
     * 全部导出
     * @param response
     */
    private void excelBigDaochu(HttpServletResponse response) {
        //查询数据库，获取数据
        //把查询数据用poi写入Excel
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/中基华企业库(全部).xlsx");
        try {
            //获取excel对象
            XSSFWorkbook excel=new XSSFWorkbook(in);
            //定义sheet页名称和对应的status值的映射关系
            Map<String, Integer> sheetMap = new HashMap<>();
            sheetMap.put("新能源光伏、风电EPC", 2);
            sheetMap.put("环保工程", 3);
            sheetMap.put("建筑工程施工总承包", 4);
            sheetMap.put("钢结构工程", 5);
            sheetMap.put("园林设计、绿化养护", 6);
            sheetMap.put("水利水电工程", 7);
            sheetMap.put("市政工程", 8);
            sheetMap.put("电力工程", 9);
            sheetMap.put("机电工程", 10);
            sheetMap.put("消防设施工程", 11);
            sheetMap.put("铁路工程", 12);
            sheetMap.put("公路工程", 13);
            sheetMap.put("桥梁工程", 14);
            sheetMap.put("隧道工程", 15);
            sheetMap.put("矿山", 16);
            sheetMap.put("桥梁", 17);
            sheetMap.put("特种工程、设备生产", 18);
            sheetMap.put("机场、航道、港口", 19);
            sheetMap.put("石油化工", 20);
            sheetMap.put("装饰装修", 21);
            sheetMap.put("防水防腐", 22);
            sheetMap.put("运行维护工程", 23);
            sheetMap.put("冶金", 24);
            sheetMap.put("施工劳务", 25);
            sheetMap.put("生态地质矿山勘察", 26);
            sheetMap.put("拆除爆破", 27);
            sheetMap.put("电子与智能化", 28);
            sheetMap.put("河湖治理", 29);
            sheetMap.put("混凝土", 30);
            sheetMap.put("起重设备", 31);
            sheetMap.put("通信工程", 32);
            sheetMap.put("设计", 33);
            sheetMap.put("电缆电路", 34);
            sheetMap.put("城市及道路照明",35 );
            sheetMap.put("保安", 36);
            sheetMap.put("环卫", 37);
            sheetMap.put("监理", 38);
            sheetMap.put("造价", 39);
            sheetMap.put("审计", 40);
            sheetMap.put("招标代理", 41);
            sheetMap.put("采购代理", 42);
            sheetMap.put("物业", 43);
            sheetMap.put("网络通讯", 45);
            sheetMap.put("工程咨询", 46);
            sheetMap.put("安全评估", 47);
            sheetMap.put("家政", 48);
            sheetMap.put("道路运输", 49);
            sheetMap.put("餐饮", 50);
            sheetMap.put("土石方", 51);
            sheetMap.put("设备", 52);
            sheetMap.put("岩土工程", 53);
            sheetMap.put("工程测量", 54);
            sheetMap.put("水文地质", 55);
            sheetMap.put("生态环境环境工程", 56);
            sheetMap.put("土木工程", 57);
            sheetMap.put("其他", 44);

            //遍历映射关系，填充数据到对应的sheet页
            for (Map.Entry<String, Integer> entry : sheetMap.entrySet()) {
                String sheetName = entry.getKey();
                int status = entry.getValue();
                //获取数据
                List<CompleteEx> dataList = fileService.getByStatus(status);
                //获取sheet页
                XSSFSheet sheet = excel.getSheet(sheetName);
                //填充数据
                XSSFRow row ;
                int i=1;
                for (CompleteEx completeEx : dataList){
                    //获得某一行
                    row=sheet.getRow(i)!= null ? sheet.getRow(i) : sheet.createRow(i);
                    // 填充数据到单元格
                    createCellIfNotExists(sheet, row, 0).setCellValue(completeEx.getQname());
                    createCellIfNotExists(sheet, row, 1).setCellValue(completeEx.getQposition());
                    createCellIfNotExists(sheet, row, 2).setCellValue(completeEx.getNumber());
                    createCellIfNotExists(sheet, row, 3).setCellValue(completeEx.getDate());
                    createCellIfNotExists(sheet, row, 4).setCellValue(completeEx.getFname());
                    createCellIfNotExists(sheet, row, 5).setCellValue(completeEx.getFtype());
                    createCellIfNotExists(sheet, row, 6).setCellValue(completeEx.getAdress());
                    createCellIfNotExists(sheet, row, 7).setCellValue(completeEx.getPrice());
                    createCellIfNotExists(sheet, row, 8).setCellValue(completeEx.getLperson());
                    createCellIfNotExists(sheet, row, 9).setCellValue(completeEx.getCperson());
                    createCellIfNotExists(sheet, row, 10).setCellValue(completeEx.getCposition());
                    createCellIfNotExists(sheet, row, 11).setCellValue(completeEx.getCphone());
                    createCellIfNotExists(sheet, row, 12).setCellValue(completeEx.getRperson());
                    createCellIfNotExists(sheet, row, 13).setCellValue(completeEx.getRphone());
                    i=i+1;


                }

            }

            //通过输出流将Excel下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    // 创建单元格（如果单元格不存在）
    private XSSFCell createCellIfNotExists(XSSFSheet sheet,XSSFRow row, int columnIndex) {
        XSSFCell cell = row.getCell(columnIndex);
        // 获取第二行的样式
        XSSFRow secondRow = sheet.getRow(1);
        XSSFCellStyle style = secondRow.getCell(columnIndex).getCellStyle();
        if (cell == null) {
            cell = row.createCell(columnIndex);
            // 应用样式到单元格
            cell.setCellStyle(style);
        }
        return cell;
    }
    private void excelSmallDaochu(HttpServletResponse response, List<CompleteEx> list) {
        //查询数据库，获取数据
        //把查询数据用poi写入Excel
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/中基华企业库.xlsx");
        try {
            XSSFWorkbook excel=new XSSFWorkbook(in);
            //获取Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充明细数据
            XSSFRow row ;
            int i=1;
            for (CompleteEx completeEx : list){
                //获得某一行
                row=sheet.getRow(i)!= null ? sheet.getRow(i) : sheet.createRow(i);
                // 填充数据到单元格
                createCellIfNotExists(sheet, row, 0).setCellValue(completeEx.getQname());
                createCellIfNotExists(sheet, row, 1).setCellValue(completeEx.getQposition());
                createCellIfNotExists(sheet, row, 2).setCellValue(completeEx.getNumber());
                createCellIfNotExists(sheet, row, 3).setCellValue(completeEx.getDate());
                createCellIfNotExists(sheet, row, 4).setCellValue(completeEx.getFname());
                createCellIfNotExists(sheet, row, 5).setCellValue(completeEx.getFtype());
                createCellIfNotExists(sheet, row, 6).setCellValue(completeEx.getAdress());
                createCellIfNotExists(sheet, row, 7).setCellValue(completeEx.getPrice());
                createCellIfNotExists(sheet, row, 8).setCellValue(completeEx.getLperson());
                createCellIfNotExists(sheet, row, 9).setCellValue(completeEx.getCperson());
                createCellIfNotExists(sheet, row, 10).setCellValue(completeEx.getCposition());
                createCellIfNotExists(sheet, row, 11).setCellValue(completeEx.getCphone());
                createCellIfNotExists(sheet, row, 12).setCellValue(completeEx.getRperson());
                createCellIfNotExists(sheet, row, 13).setCellValue(completeEx.getRphone());
                i=i+1;
            }



            //通过输出流将Excel下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
